<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入绘本集标题"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="分类" prop="categoryId">
        <el-select v-model="queryParams.categoryId" placeholder="请选择分类" clearable class="!w-240px">
          <el-option
            v-for="category in categoryList"
            :key="category.id"
            :label="category.name"
            :value="category.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="语言" prop="language">
        <el-select v-model="queryParams.language" placeholder="请选择语言" clearable class="!w-240px" @change="handleLanguageChange">
          <el-option label="英文" value="en" />
          <el-option label="中文" value="zh" />
        </el-select>
      </el-form-item>
      <el-form-item label="难度" prop="difficultyLevel">
        <el-select v-model="queryParams.difficultyLevel" placeholder="请选择难度" clearable class="!w-240px">
          <el-option label="入门" value="beginner" />
          <el-option label="初级" value="elementary" />
          <el-option label="中级" value="intermediate" />
          <el-option label="高级" value="advanced" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="isActive">
        <el-select v-model="queryParams.isActive" placeholder="请选择状态" clearable class="!w-240px">
          <el-option label="启用" :value="true" />
          <el-option label="禁用" :value="false" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleBatchEnable"
          :disabled="!hasSelection"
        >
          <Icon icon="ep:check" class="mr-5px" /> 批量启用
        </el-button>
        <el-button
          type="warning"
          plain
          @click="handleBatchDisable"
          :disabled="!hasSelection"
        >
          <Icon icon="ep:close" class="mr-5px" /> 批量禁用
        </el-button>
        <el-button
          type="danger"
          plain
          @click="handleBatchDelete"
          :disabled="!hasSelection"
        >
          <Icon icon="ep:delete" class="mr-5px" /> 批量删除
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="id" />
      <el-table-column label="封面" align="center" prop="cover" width="100">
        <template #default="scope">
          <img v-if="scope.row.cover" :src="scope.row.cover" alt="封面" class="h-16 w-16 object-cover rounded" />
          <span v-else class="text-gray-400">无封面</span>
        </template>
      </el-table-column>
      <el-table-column label="标题" align="center" prop="title" />
      <el-table-column label="分类" align="center" prop="categoryId">
        <template #default="scope">
          <span>{{ getCategoryName(scope.row.categoryId) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="语言" align="center" prop="language">
        <template #default="scope">
          <el-tag :type="scope.row.language === 'en' ? 'primary' : 'success'">
            {{ scope.row.language === 'en' ? '英文' : '中文' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="难度" align="center" prop="difficultyLevel">
        <template #default="scope">
          <el-tag :type="getDifficultyTagType(scope.row.difficultyLevel)">
            {{ getDifficultyText(scope.row.difficultyLevel) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="绘本数量" align="center" prop="bookCount" />
      <el-table-column label="适龄范围" align="center" prop="ageRange" />
      <el-table-column label="状态" align="center" prop="isActive">
        <template #default="scope">
          <el-tag :type="scope.row.isActive ? 'success' : 'danger'">
            {{ scope.row.isActive ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" width="200">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <el-dialog
    v-model="dialog.visible"
    :title="dialog.title"
    width="90%"
    :close-on-click-modal="false"
    class="bookset-dialog"
  >
    <BookSetManager
      v-if="dialog.visible"
      :book-set-id="dialog.bookSetId"
      :mode="dialog.mode"
      @close="dialog.visible = false"
      @success="handleCreateSuccess"
    />
  </el-dialog>
</template>

<script setup lang="ts">
import { dateFormatter } from '@/utils/formatTime'
import * as BookSetApi from '@/api/reading/bookset'
import * as CategoryApi from '@/api/reading/category'
import BookSetManager from './BookSetManager.vue'

/** 绘本集管理 */
defineOptions({ name: 'BookSetManagement' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数据
const categoryList = ref<any[]>([]) // 分类列表
const selectedIds = ref<number[]>([]) // 选中的ID列表
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  title: undefined,
  categoryId: undefined,
  language: undefined,
  difficultyLevel: undefined,
  isActive: undefined
})
const queryFormRef = ref() // 搜索的表单
const dialog = reactive({
  visible: false,
  title: '',
  bookSetId: null as number | null,
  mode: 'create' as 'create' | 'edit'
})

// 是否有选中项
const hasSelection = computed(() => selectedIds.value.length > 0)

/** 获取分类列表 */
const getCategoryList = async () => {
  try {
    const data = await CategoryApi.getActiveCategoryList()
    categoryList.value = data
  } catch (error) {
    console.error('获取分类列表失败:', error)
  }
}

/** 根据分类ID获取分类名称 */
const getCategoryName = (categoryId: number) => {
  const category = categoryList.value.find((item: any) => item.id === categoryId)
  return category ? category.name : '未知分类'
}

// 注意：文件URL由后端直接返回完整地址，前端不再进行URL转换

/** 语言变化处理 */
const handleLanguageChange = () => {
  // 语言变化时重置分类选择
  queryParams.categoryId = undefined
  // 重新获取对应语言的分类列表
  getCategoryList()
  // 重新查询
  handleQuery()
}

/** 表格选择变化 */
const handleSelectionChange = (selection: any[]) => {
  selectedIds.value = selection.map(item => item.id)
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await BookSetApi.getBookSetPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const openForm = (type: string, id?: number) => {
  dialog.visible = true
  dialog.title = type === 'create' ? '创建绘本集' : '修改绘本集'
  dialog.mode = type === 'create' ? 'create' : 'edit'
  dialog.bookSetId = id || null
}

/** 批量启用 */
const handleBatchEnable = async () => {
  try {
    await message.confirm('确定要启用选中的绘本集吗？')
    await BookSetApi.batchUpdateBookSetStatus(selectedIds.value, true)
    message.success('批量启用成功')
    selectedIds.value = []
    await getList()
  } catch (error) {
    console.error('批量启用失败:', error)
  }
}

/** 批量禁用 */
const handleBatchDisable = async () => {
  try {
    await message.confirm('确定要禁用选中的绘本集吗？')
    await BookSetApi.batchUpdateBookSetStatus(selectedIds.value, false)
    message.success('批量禁用成功')
    selectedIds.value = []
    await getList()
  } catch (error) {
    console.error('批量禁用失败:', error)
  }
}

/** 批量删除 */
const handleBatchDelete = async () => {
  try {
    await message.delConfirm(`确定要删除选中的 ${selectedIds.value.length} 个绘本集吗？`)
    await BookSetApi.batchDeleteBookSet(selectedIds.value)
    message.success('批量删除成功')
    selectedIds.value = []
    await getList()
  } catch (error) {
    console.error('批量删除失败:', error)
  }
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await BookSetApi.deleteBookSet(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 创建成功处理 */
const handleCreateSuccess = () => {
  dialog.visible = false
  getList()
}

/** 获取难度标签类型 */
const getDifficultyTagType = (difficulty: string) => {
  const typeMap = {
    'beginner': 'success',
    'elementary': 'primary',
    'intermediate': 'warning',
    'advanced': 'danger'
  }
  return typeMap[difficulty] || 'info'
}

/** 获取难度文本 */
const getDifficultyText = (difficulty: string) => {
  const textMap = {
    'beginner': '入门',
    'elementary': '初级',
    'intermediate': '中级',
    'advanced': '高级'
  }
  return textMap[difficulty] || difficulty
}

/** 初始化 **/
onMounted(() => {
  getCategoryList()
  getList()
})
</script>

<style scoped>
.bookset-dialog {
  .el-dialog__body {
    padding: 0;
  }
}
</style>
